package com.suyeer.basic.util;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author jun 2018/10/19
 */
public class FileUtil {

    private final static int HEAD_NUM1 = -2;
    private final static int HEAD_NUM2 = -17;
    private final static int HEAD_NUM3 = -69;
    private final static int HEAD_NUM4 = -65;
    private final static int HEAD_IDX = 2;

    public static String readFileToString(File file) throws Exception {
        return FileUtils.readFileToString(file, ConstUtil.DEFAULT_ENCODE);
    }

    public static String readFileToString(File file, boolean autoAdapterCode) throws Exception {
        String code = ConstUtil.DEFAULT_ENCODE;
        if (autoAdapterCode) {
            code = getCode(file);
        }
        return FileUtils.readFileToString(file, code);
    }

    public static String getCode(File file) throws Exception {
        InputStream inputStream = new FileInputStream(file);
        byte[] head = new byte[3];
        inputStream.read(head);
        String code = "gb2312";
        if (head[0] == -1 && head[1] == HEAD_NUM1) {
            code = "UTF-16";
        } else if (head[0] == HEAD_NUM1 && head[1] == -1) {
            code = "Unicode";
        } else if (head[0] == HEAD_NUM2 && head[1] == HEAD_NUM3 && head[HEAD_IDX] == HEAD_NUM4) {
            code = "UTF-8";
        }
        inputStream.close();
        return code;
    }
}